//>>risc
 ========================================================
// INTEGER DIVISION WITH QUOTIENT AND REMAINDER
//
// Calculates:
//
//     137 / 12 = 11 remainder 5
//
// THIS PROGRAM DEMONSTRATES:
//
//   1. Calling a function with JAL.
//   2. Returning from a function with JALR.
//   3. Passing arguments in registers.
//   4. Returning multiple results in registers.
//   5. Division using repeated subtraction.
//   6. Creating a loop with BLT and JAL.
//   7. Detecting division by zero.
//   8. Using a status register to report an error.
//   9. Using ADD to copy register values.
//  10. Using ADDI to initialize and increment values.
//
// REGISTER USE:
//
//   x1  = return address
//   x10 = dividend
//   x11 = divisor
//   x12 = quotient
//   x13 = remainder
//   x14 = error status: 0 = valid, 1 = divide by zero
//
// EXPECTED OUTPUT:
//
//   Dividend  = 137
//   Divisor   = 12
//   Quotient  = 11
//   Remainder = 5
// ========================================================

start:
        addi  x10, x0, 137        // Dividend
        addi  x11, x0, 12         // Divisor

        jal   x1, Divide          // Call division function

        bne   x14, x0, DivideError

        cout  << "Dividend  = " << x10 << endl
        cout  << "Divisor   = " << x11 << endl
        cout  << "Quotient  = " << x12 << endl
        cout  << "Remainder = " << x13 << endl

        jal   x0, EndProgram


// --------------------------------------------------------
// Divide
//
// Input:
//
//   x10 = dividend
//   x11 = divisor
//
// Output:
//
//   x12 = quotient
//   x13 = remainder
//   x14 = error status
// --------------------------------------------------------

Divide:
        addi  x12, x0, 0          // Quotient starts at zero
        add   x13, x10, x0        // Remainder starts as dividend
        addi  x14, x0, 0          // Clear error status

        beq   x11, x0, ZeroError  // Check for division by zero


// Continue subtracting while remainder >= divisor.

DivideLoop:
        blt   x13, x11, DivideDone

        sub   x13, x13, x11       // Remainder -= divisor
        addi  x12, x12, 1         // Quotient++

        jal   x0, DivideLoop


// Return the quotient and remainder.

DivideDone:
        jalr  x0, 0(x1)


// Report division by zero.

ZeroError:
        addi  x14, x0, 1          // Set error status
        jalr  x0, 0(x1)


// Display an error if the divisor was zero.

DivideError:
        cout  << "Error: division by zero" << endl

EndProgram:
